﻿@page "/_Student/Student/Edit/{id}"
@using WBBvNext.ViewModel._Student.StudentVMs;
@inherits BasePage

<ValidateForm @ref="vform" Model="@Model" OnValidSubmit="@Submit">
    <Row ItemsPerRow="ItemsPerRow.Two" RowType="RowType.FormRow">

        <BootstrapInput @bind-Value="@Model.Entity.LoginName" />
        <BootstrapInput @bind-Value="@Model.Entity.Password" />
        <BootstrapInput @bind-Value="@Model.Entity.Name" />
        <BootstrapInput @bind-Value="@Model.Entity.CellPhone" />
        <BootstrapInput @bind-Value="@Model.Entity.ZipCode" />
        <DateTimePicker @bind-Value="@Model.Entity.EnRollDate" />
        <WTUploadImage @bind-Value="@Model.Entity.PhotoId" CSKey="School" OnBeforeDelete="OnBeforeDelete" />
        <Row ColSpan="2">
            <Transfer @bind-Value="@Model.SelectedStudentMajorIDs" Items="@AllMajors" />
        </Row>
    </Row>
    <div class="modal-footer table-modal-footer">
        <Button Color="Color.Primary" Icon="fa fa-save" Text="@WtmBlazor.Localizer["Sys.Close"]" OnClick="OnClose" />
        <Button Color="Color.Primary" ButtonType="ButtonType.Submit" Icon="fa fa-save" Text="@WtmBlazor.Localizer["Sys.Edit"]" IsAsync="true" />
    </div>
</ValidateForm>

@code {

    private StudentVM Model = null;
    private ValidateForm vform { get; set; }
    [Parameter]
    public string id { get; set; }

    private List<SelectedItem> AllMajors = new List<SelectedItem>();


    protected override async Task OnInitializedAsync()
    {

        AllMajors = await WtmBlazor.Api.CallItemsApi("/api/Student/GetMajors");

        var rv = await WtmBlazor.Api.CallAPI<StudentVM>($"/api/Student/{id}");
        Model = rv.Data;
        await base.OnInitializedAsync();
    }

    private async Task<bool> OnBeforeDelete(string id)
    {
        var dc = WtmBlazor.ConfigInfo.CreateDC("School");
        var student = dc.Set<WBBvNext.School.Model.Student>().FirstOrDefault(m => m.ID == Model.Entity.ID);
        student.PhotoId = null;
        var result = await dc.SaveChangesAsync();
        return result > 0;
    }

    private async Task Submit(EditContext context)
    {
        await PostsForm(vform, $"/api/Student/edit", (s) => "Sys.OprationSuccess", method: HttpMethodEnum.PUT);
    }

    public void OnClose()
    {
        CloseDialog();
    }

}
